<?php
namespace Admin\Controller;
use Admin\Common\Page;

require_once COMMON_PATH . 'WxpayAPI/example/WxPay.JsApiPay.php';

class ActivityRefundController extends BaseController
{
    public function index()
    {
        $map['a.refund_id'] = array("neq",0);
//        $keywords = I('get.keywords');
//        if (!empty($keywords)) {
//            $map['title'] = ['like', "%$keywords%"];
////            $map['_logic'] = 'OR';
//        }

        $count = M('activity_apply')->alias('a')->where($map)->count();// 查询满足要求的总记录数
        $Page = new  Page($count, C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
//        $where['keywords'] = $keywords;
//        foreach ($where as $key => $val) {
//            $Page->parameter[$key] = urlencode($val);
//        }
        $show = $Page->show();// 分页显示输出
        $this->assign('page', $show);// 赋值分页输出

        $data = M('activity_apply')->alias('a')
            ->join("left join refund b on a.refund_id = b.refund_id")
            ->join("left join activity c on a.activity_id = c.activity_id")
            ->join("left join card d on a.user_id = d.user_id")
            ->field("
                a.apply_id,
                b.status,b.money,b.money_real,
                c.activity_id,c.title,c.a_logo,c.apply_start,c.apply_end,c.activity_start,c.activity_end,c.apply_num,c.apply_total,c.price_apply,c.price_material,c.num_deduct,
                d.card_id
            ")
            ->where($map)
            ->order('a.refund_id desc')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->data = $data;


        $this->display();
    }

    //同意退款
    public function agreed(){
        $apply_id = I('get.apply_id');
        $Acta=M('View_activity_apply');
        $Acta->startTrans();

        $apply = $Acta->where(["apply_id"=>$apply_id])->find();//活动报名信息
        $refund = M('refund')->where(["refund_id"=>$apply['refund_id']])->find();//退款信息

//        var_dump($refund);exit;

        //更改活动信息  报名人数-1
        $ra=M('Activity')->where(['activity_id'=>$apply['activity_id']])->setInc('apply_num',1);
        if(!$ra){
            $Acta->rollback();
            $this->error('系统错误,更改活动数据错误！');
        }
        //更改会员卡可免次数
        if($apply['is_applyfree']>0){
            $rc=M('Card')->where(['user_id'=>$apply['user_id']])->setInc('num_activity',$apply['num_deduct']);
            if(!$rc){
                $Acta->rollback();
                $this->error('系统错误,更改活动数据错误！');
            }
        }
        //修改 【退款订单】状态 与 【报名订单】状态
        $rr=M('refund')->where(['refund_id'=>$apply['refund_id']])->data(['status'=>1,'money_real'=>$refund['money']])->save();
        $raa=M('activity_apply')->where(['apply_id'=>$apply['apply_id']])->data(['is_refund'=>1])->save();
        if(!$rr || !$raa){
            $Acta->rollback();
            $this->error('系统错误,更改活动数据错误！');
        }


        //执行退款，然后提交
        $input = new \WxPayRefund();
        $input->SetOut_trade_no(\WxPayConfig::MCHID . $apply['pay_id']);
        $input->SetTotal_fee($refund['money']*100);
        $input->SetRefund_fee($refund['money']*100);
        $input->SetOut_refund_no(\WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOp_user_id(\WxPayConfig::MCHID);
//        $input->SetRefund_account(true);
        $res = \WxPayApi::refund($input);

        if($res['return_code'] != "SUCCESS"){   //判断是否连接成功
            $Acta->rollback();
            $this->error('系统错误，连接失败！');
        }
        if($res['result_code'] != "SUCCESS"){   //判断业务是否成功
            $Acta->rollback();
            $this->error($res['err_code_des']);
        }

//        var_dump($res);exit;

        /* 失败
         * array(9) {
            ["appid"]=> "wxc381b6c916cd12e0"
            ["err_code"]=>"NOTENOUGH"
            ["err_code_des"]=> "交易未结算资金不足，请使用可用余额退款"
            ["mch_id"]=> "1243290602"
            ["nonce_str"]=> "HgFLMWkSdYiwRGgq"
            ["result_code"]=>"FAIL"
            ["return_code"]=>"SUCCESS"
            ["return_msg"]=>"OK"
            ["sign"]=> "26B8E30163070F9DA9BA97253565801D"
        }*/

        /* 成功
         * array(18) {
            ["appid"]=> "wxc381b6c916cd12e0"
            ["cash_fee"]=>"1"
            ["cash_refund_fee"]=>"1"
            ["coupon_refund_count"]=>"0"
            ["coupon_refund_fee"]=>"0"
            ["mch_id"]=> "1243290602"
            ["nonce_str"]=> "FxCk9lN7gf3piKiJ"
            ["out_refund_no"]=> "124329060220170109110733"
            ["out_trade_no"]=> "124329060216846244"
            ["refund_channel"]=>
              array(0) {
                        }
            ["refund_fee"]=>"1"
            ["refund_id"]=> "2009572001201701090729097526"
            ["result_code"]=>"SUCCESS"
            ["return_code"]=>"SUCCESS"
            ["return_msg"]=>"OK"
            ["sign"]=> "E740C66F27CD12ACEABD3E613DCDA09E"
            ["total_fee"]=>"1"
            ["transaction_id"]=> "4009572001201701055239240150"
        }*/
        
        $Acta->commit();
        $this->success('退款成功！');

    }

    //拒绝退款
    public function refuse(){
        $apply_id = I('get.apply_id');
        $refund_id = M("activity_apply")->where(["apply_id"=>$apply_id])->getField("refund_id");
        $ret = M('refund')->where(["refund_id"=>$refund_id])->data(["status"=>3])->save();
        if($ret) {
            $this->success('拒绝退款成功！');
        } else {
            $this->error('拒绝退款失败，请联系管理员！');
        }
    }

}